package com.foryang.springcloud.util;


import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;


public class FastDFSUtil {

    private static TrackerClient trackerClient;
    private static TrackerServer trackerServer;
    private static StorageServer storageServer;

    static {
        try {
            String configPath = new ClassPathResource("fastdfs-client.properties").getFile().getAbsolutePath();
            ClientGlobal.initByProperties(configPath);
            trackerClient = new TrackerClient();
            trackerServer = trackerClient.getConnection();
            storageServer = trackerClient.getStoreStorage(trackerServer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String[] upload(InputStream inputStream, String fileName){
        if(inputStream == null) {
            return null;
        }
        String[] result = null;
        try {
            NameValuePair[] list = new NameValuePair[2];
            list[0] = new NameValuePair("fileName",fileName);
            list[1] = new NameValuePair("context", inputStream.available()+"");
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);

            StorageClient storageClient = new StorageClient(trackerServer,storageServer);
            result =storageClient.upload_file(buffer, StringUtils.getFilenameExtension(fileName),list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static byte[] download(String group, String remoteFilename) {
        StorageClient storageClient = new StorageClient(trackerServer, storageServer);
        byte[] value = null;
        try {
            value = storageClient.download_file(group, remoteFilename);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

}
